from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QAction, QTableView, QMenu
from PyQt5.QtSql import QSqlRecord

from RBK.View.AddDialog    import AddDialog
from RBK.View.RemoveDialog import RemoveDialog

#For DataType Models

# For Data Models
from RBK.Delegate.Calculation import Calculation
from RBK.Delegate.Decimal     import Decimal
from RBK.Delegate.Integer     import Integer
from RBK.Delegate.PullDown    import PullDown
from RBK.Delegate.Text        import Text
from RBK.Delegate.TrueFalse   import TrueFalse 


class Table(QTableView):
    fieldAdded = pyqtSignal(str, str)
    fieldRemoved = pyqtSignal(str, str)
    
    def __init__(self):
        super().__init__()

    def contextMenuEvent(self, event):
        if(self.model().tableName().split()[0]=='Struct'):
            m = QMenu()
            m.addAction('Add new field', self.addFieldClicked)

            #If right clicked on a row, give the option to delete the line.
            index = self.indexAt(event.pos())
            if(index.row() == -1):
                event.accept()
                m.exec(event.globalPos())
            else:
                header = self.model().headerData(0, Qt.Horizontal)
                field = self.model().record(index.row()).value(header)
                m.addAction('Remove field {0}'.format(field), self.removeFieldClicked)
                m.exec(event.globalPos())


    def addFieldClicked(self):
        ad = AddDialog(self, self.model())
        ad.added.connect(self.addField)
        ad.exec()

    @pyqtSlot(str, str)
    def addField(self, table, text):
        self.fieldAdded.emit(table, text)


    def removeFieldClicked(self):
        field = self.selectedIndexes()[0].data()

        rd = RemoveDialog(self, self.model(), field)
        rd.removed.connect(self.removeField)
        rd.exec()

    @pyqtSlot(str, str)
    def removeField(self, typename, field):
        row = self.selectedIndexes()[0].row()
        
        index = self.model().index(row-1, 0)
        self.fieldRemoved.emit(typename, field)
        self.setCurrentIndex(index)
